﻿// PEResouceEdit.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <windows.h>
#include <stdio.h>

#pragma warning(disable:4996)

#pragma pack(push)
#pragma pack(2)
struct ICONDIR
{
    WORD idReserved;
    WORD idType;
    WORD idCount;
    //ICONDIRENTRY idEntries[];
};
struct ICONDIRENTRY
{
    BYTE bWidth;
    BYTE bHeight;
    BYTE bColorCount;
    BYTE bReserved;
    WORD wPlanes;
    WORD wBitCount;
    DWORD dwBytesInRes;
    DWORD dwImageOffset;
};
struct GRPICONDIRENTRY
{
    BYTE bWidth;
    BYTE bHeight;
    BYTE bColorCount;
    BYTE bReserved;
    WORD wPlanes;
    WORD wBitCount;
    DWORD dwBytesInRes;
    WORD nID;
};
struct GRPICONDIR
{
    WORD idReserved;
    WORD idType;
    WORD idCount;
    GRPICONDIRENTRY entry;
};
#pragma pack(pop)

int UpdateIcon(ICONDIRENTRY* pEntry, int gID, int nID, int langID, BYTE* pbImg, int cbImg)
{
    HANDLE hdst = NULL;
    BOOL rv = FALSE;
    GRPICONDIR pe_dir = { 0 };
    pe_dir.idType = 1;
    pe_dir.idCount = 1;
    pe_dir.entry.bWidth = pEntry->bWidth;
    pe_dir.entry.bHeight = pEntry->bHeight;
    pe_dir.entry.bColorCount = pEntry->bColorCount;
    pe_dir.entry.wPlanes = pEntry->wPlanes;
    pe_dir.entry.wBitCount = pEntry->wBitCount;
    pe_dir.entry.dwBytesInRes = pEntry->dwBytesInRes;
    pe_dir.entry.nID = nID;

    hdst = BeginUpdateResource("C:\\Users\\firexmoon\\gitee\\editPEResource\\WDUSBKeyTool.exe", FALSE);
    if (!hdst)
        return -1;
    rv = UpdateResource(hdst, RT_ICON, MAKEINTRESOURCE(nID), langID, pbImg, cbImg);
    if (!rv)
        return -1;
    rv = UpdateResource(hdst, RT_GROUP_ICON, MAKEINTRESOURCE(gID), langID, &pe_dir, sizeof(pe_dir));
    if (!rv)
        return -1;
    rv = EndUpdateResource(hdst, FALSE);
    if (!rv)
        return -1;

    return 0;
}


int main()
{
    FILE* pfile = NULL;

    pfile = fopen("C:\\Users\\firexmoon\\gitee\\editPEResource\\win-install.ico", "rb");
    if (!pfile)
    {
        printf("error:");
        return -1;
    }

    ICONDIR icon_dir = { 0 };
    fread(&icon_dir, 1, sizeof(icon_dir), pfile);

    for (int i = 0; i < icon_dir.idCount; i++)
    {
        ICONDIRENTRY icon_entry = { 0 };
        fread(&icon_entry, 1, sizeof(icon_entry), pfile);

        if (icon_entry.bWidth == 32)
        {
            fseek(pfile, icon_entry.dwImageOffset, SEEK_SET);
            BYTE* pImg = new BYTE[icon_entry.dwBytesInRes];
            fread(pImg, 1, icon_entry.dwBytesInRes, pfile);
            //UpdateIcon(&icon_entry, 4008, 1, 2052, pImg, icon_entry.dwBytesInRes);
            UpdateIcon(&icon_entry, 128, 1, 2052, pImg, icon_entry.dwBytesInRes);
            UpdateIcon(&icon_entry, 141, 2, 2052, pImg, icon_entry.dwBytesInRes);
            delete[] pImg;
            break;
        }

    }


    fclose(pfile);

}
